package com.tang.calculator.symbols;

import com.tang.calculator.context.CalculateContext;
import com.tang.calculator.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

/**
 * @ClassName: EquivalentSymbol
 * @Author: freedu
 * @Date: 2021/3/17 14:38
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class EquivalentSymbol implements OperatorSymbol, Calculation {
    @Autowired
    ValueSymbolFactory valueSymbolFactory;
    @Autowired
    CheckUtils checkUtils;

    @Override
    public int getPriority() {
        return 5;
    }

    @Override
    public void simpleOperate(CalculateContext context) {
        Stack<ValueSymbol> valueStack = context.getValueStack();
        ValueSymbol value1 = valueStack.pop();
        ValueSymbol value2 = valueStack.pop();

        BigDecimal res;

        if ((value1 instanceof StringValueSymbol && (value2 instanceof BigDecimalValueSymbol))
                || (value2 instanceof StringValueSymbol && (value1 instanceof BigDecimalValueSymbol))) {
            res = BigDecimal.ZERO;
            ValueSymbol valueSymbol = valueSymbolFactory.create(res.toString());
            valueStack.push(valueSymbol);
            return;
        }

        if (value1.getValue().compareTo(value2.getValue()) == 0) {
            res = BigDecimal.ONE;
        } else {
            res = BigDecimal.ZERO;
        }
        ValueSymbol valueSymbol = valueSymbolFactory.create(res.toString());

        valueStack.push(valueSymbol);
    }

    @Override
    public String getName() {
        return "==";
    }

    /**
     * 校验
     *
     * @param context
     * @return
     */
    @Override
    public String check(CalculateContext context, String str) {
        if (context.getFormula().contains(getName())) {
            return checkUtils.coordinate(context, str, getName());
        }
        return null;
    }
}
